package com.dandy.helper.java.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * <pre>
 *     SmallEndian即little endian 解读：<a href="http://blog.chinaunix.net/uid-21651805-id-3475144.html">BIG Endian 和 Small Endian模式的区别 </a>
 *     自己开发的符合SmallEndian字节顺序的处理流
 *     SmallEndian means little endian ,know more:<a href="http://blog.chinaunix.net/uid-21651805-id-3475144.html">BIG Endian 和 Small Endian模式的区别 </a>
 *     an InputStream class that we coded for the little endian byte order
 * </pre>
 * <pre>
 * Created by BN
 * Wechat: flycatdeng
 * </pre>
 */
public class SmallEndianInputStream {
    private InputStream is;  //封装的输入流

    public SmallEndianInputStream(InputStream is) {
        this.is = is;
    }

    /**
     * 以SmallEndian字节顺序读取一个32位整数并返回
     *
     * @return
     * @throws IOException
     */
    public int readInt() throws IOException {
        byte[] buff = new byte[4];
        is.read(buff);
        return (buff[3] << 24)
                + ((buff[2] << 24) >>> 8)
                + ((buff[1] << 24) >>> 16)
                + ((buff[0] << 24) >>> 24);
    }

    /**
     * 以SmallEndian字节顺序读取一个16位无符号整数并返回
     *
     * @return
     * @throws IOException
     */
    public int readUnsignedShort() throws IOException {
        byte[] buff = new byte[2];
        is.read(buff);
        return ((buff[1] << 24) >>> 16)
                + ((buff[0] << 24) >>> 24);
    }

    /**
     * 读取一个字节
     *
     * @return
     * @throws IOException
     */
    public byte readByte() throws IOException {
        return (byte) is.read();
    }

    /**
     * 读取一个浮点数
     *
     * @return
     * @throws IOException
     */
    public final float readFloat() throws IOException {
        return Float.intBitsToFloat(this.readInt());
    }

    /*
     * 读取字节数组
     */
    public int read(byte[] buff) throws IOException {
        int count = this.is.read(buff);
        return count;
    }

    /*
     * 读取字符串
     */
    public String readString(int length) throws IOException {
        byte[] buff = new byte[length];
        this.is.read(buff);
        return this.makeSafeString(buff);
    }

    /**
     * 将字节数组中的数据安全地转化为字符串并返回
     *
     * @param buffer
     * @return
     */
    public String makeSafeString(byte buffer[]) {
        final int len = buffer.length;
        for (int i = 0; i < len; i++) {
            if (buffer[i] == (byte) 0) {
                return new String(buffer, 0, i);
            }
        }
        return new String(buffer).trim();
    }

    /*
     * 关闭流
     */
    public void close() throws IOException {
        if (is != null)
            is.close();
    }
}